// 兼容 cjs, rollup默认情况下只会处理es module
const commonjs = require("@rollup/plugin-commonjs");
const nodeResolve = require("@rollup/plugin-node-resolve");

// 使用代码转换和压缩
const { babel } = require("@rollup/plugin-babel");
const terser = require("@rollup/plugin-terser");

// html css image
const html = require("@rollup/plugin-html");
const postcss = require("rollup-plugin-postcss");
const postcssPresetEnv = require("postcss-preset-env");
const image = require("@rollup/plugin-image");

// vue
const vue = require("rollup-plugin-vue");
const replace = require("@rollup/plugin-replace");

// 开发服务器
const serve = require("rollup-plugin-serve");
const livereload = require("rollup-plugin-livereload");

const basePlugins = [
    commonjs(),
    nodeResolve(),
    babel({
        babelHelpers: "bundled",
        exclude: /node_modules/
    }),
    html({
        // publicPath: "/",
        title: "SPA-Rollup-Template",
        template: ({ title, attributes, bundle, files, publicPath }) => {
            return `
                <!DOCTYPE html>
                <html lang="${attributes.html.lang}">
                  <head>
                    <meta charset="utf-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                    <title>${title}</title>
                  </head>
                  <body>
                    <div id="app"></div>
                    ${files.js.map(jsFile => `<script src="${publicPath}${jsFile.fileName}"></script>`).join("\n")}
                  </body>
                </html>
              `;
        }
    }),
    postcss({
        plugins: [postcssPresetEnv]
    }),
    image(),
    vue(),
    replace({
        "process.env.NODE_ENV": JSON.stringify("production"),
        preventAssignment: true
    })
];

const devPlugins = [
    serve({
        open: true, // 自动打开浏览器
        port: 8000,
        contentBase: ["dist"] // 静态服务读取的文件夹
    }),
    livereload()
];

const prodPlugins = [terser()];

module.exports = {
    // external: ["lodash"],
    input: "src/index.js",
    output: [
        {
            format: "umd",
            name: "ikunUtils",
            file: "dist/bundle.umd.js",
            globals: {
                lodash: "_"
            }
        }
    ],
    plugins: process.env.NODE_ENV === "production" ? basePlugins.concat(prodPlugins) : basePlugins.concat(devPlugins)
};
